package cn.just.food.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.just.food.entity.User;
import cn.just.food.util.JdbcUtil;

public class UserDao {

	public void addUser(User user) {
		Connection con = null;
		PreparedStatement pst = null;
		String sql = "insert into customer values(?,?,?)";
		con = JdbcUtil.getConnection();	
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, user.getNickname());
			pst.setString(2, user.getPhone());
			pst.setString(3, user.getPwd());
			pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JdbcUtil.closeCon(con);
	}
	
	public User findByPhoneAndPwd(String phone,String pwd) {
		Connection con = null;
		PreparedStatement pst = null;
		String sql = "select * from customer where phone=? and pwd=?";
		con = JdbcUtil.getConnection();
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, phone);
			pst.setString(2, pwd);
			ResultSet rs = pst.executeQuery();
			while(rs.next()) {
				User user = new User();
				user.setNickname(rs.getString(1));
				user.setPhone(rs.getString(2));
				user.setPwd(rs.getString(3));
				return user;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JdbcUtil.closeCon(con);
		return null;
	}
	
	public boolean delUser(String phone) {
		boolean flag = true;
		Connection con = null;
		PreparedStatement pst = null;
		String sql = "delete from customer where phone=?";
		con = JdbcUtil.getConnection();
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, phone);
			int num = pst.executeUpdate();
			if (num == 1) {
				flag = true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JdbcUtil.closeCon(con);
		return flag;
	}
}
